package com.xr.blackhoole.rabbit.annotation;

import com.xr.blackhoole.mvc.configuration.BlackholeIsolationConfiguration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理rabbitMQ的 queue 和rounting
 */
public class BlackholeRabbitListenerAnnotationBeanPostProcessor extends RabbitListenerAnnotationBeanPostProcessor{
    @Resource
    private BlackholeIsolationConfiguration blackholeIsolationConfiguration;
    

    /**
     * routingKey 前置处理器
     *
     * @param queueName
     * @param routingKey
     * @return
     */
    @Override
    public String preProcessingRoutingKey(String queueName, String routingKey) {
        //检查传入的队列是否是影子队列 ，是就将key也转换成影子key
        if (blackholeIsolationConfiguration.checkIsolation(queueName) && !blackholeIsolationConfiguration.checkIsolation(routingKey)){
            return blackholeIsolationConfiguration.generateIsolationKey(routingKey);
        }
        return routingKey;
    }

    /**
     * 处理队列问题，如果来了一个队列就生成一个shadow的队列
     *
     * @param queues
     * @return
     */
    @Override
    public List<String> handelQueues(List<String> queues) {
        List<String> isolationQueues=new ArrayList<>();
        if (queues!=null && !queues.isEmpty()){
            for (String queue : queues) {
                //创建影子队列
                isolationQueues.add(blackholeIsolationConfiguration.generateIsolationKey(queue));
            }
            queues.addAll(isolationQueues);
        }
        return queues;
    }
}
